#!/bin/bash	

if [ $# -ne 1 ]; then
    echo "Usage:  ./autest.sh parameter1"
    exit 1
fi

if ! command -v go &> /dev/null; then
    echo "== Download golang"
	sudo dnf install go -y
fi

LOG_DIR="${HOME}/logs/grafana"
if [ ! -d ${LOG_DIR} ]; then
	echo "== Mkdir ${LOG_DIR}"
	mkdir ${LOG_DIR}
fi

PRO_DIR=$1
cd $1
PRO_DIR=$(pwd)
echo "== project directory is ${PRO_DIR}"
grafana_path="${PRO_DIR}/grafana-main"

if [ ! -d "${grafana_path}" ]; then
	echo "Clone grafana"
	cd $PRO_DIR
	git clone https://github.com/grafana/grafana.git grafana-main

	cd $grafana_path
	yarn install --immutable
	yarn start

fi


# Run frontend tests
cd ${grafana_path}
# ../../performance_counter_920.sh "yarn test --watchAll" ${LOG_DIR}


TEST_DIR="${grafana_path}/pkg"
# Run backend tests
TABLE="${PRO_DIR}/table_grafana_backend.txt"
echo "| Test Name | Performance Name | Performance Value |" > ${TABLE}
echo "| --- | --- | --- |" >> ${TABLE}

echo "== backend test" 
cd ${TEST_DIR}
echo "entering $(pwd)"
mkdir ${LOG_DIR}/backend
for dir in *; do
	if [ -d "$dir" ]; then
		echo $dir
		# -short -timeout=30m
		${PRO_DIR}/perf_out.sh  "go test -v $(pwd)/${dir} -cover" ${LOG_DIR} ${TABLE} ${dir} &>${LOG_DIR}/backend/${dir}.log	
	fi
done

# Run SQLite, PostgreSQL and MySQL integration tests
TABLE="${PRO_DIR}/table_grafana_sql.txt"
echo "| Test Name | Performance Name | Performance Value |" > ${TABLE}
echo "| --- | --- | --- |" >> ${TABLE}

echo "== sql test" 
cd ${TEST_DIR}
echo "entering $(pwd)"
mkdir ${LOG_DIR}/sql
for dir in *; do
	if [ -d "$dir" ]; then
		echo $dir
		${PRO_DIR}/perf_out.sh  "go test -v $(pwd)/${dir} -cover -covermode=atomic -tags=integration" ${LOG_DIR} ${TABLE} ${dir} &>${LOG_DIR}/sql/${dir}.log
	fi
done


# Run end-to-end tests
sudo dnf install xorg-x11-server-Xvfb -y

cd ${grafana_path}
yarn e2e
../../performance_counter_920.sh "yarn e2e" ${LOG_DIR}
